/**
 * 页面（页面肩部）级别按钮click事件
 */
 import { print, ajax, base, promptBox, toast,pageTo,viewModel,cacheTools } from 'nc-lightapp-front';
 let { getGlobalStorage } = viewModel;
 import requestApi, { isUploadedAttachments } from '../requestApi';
 import { dataHandle ,routeChange} from '../initTemplate';
 import {imageScan, imageView} from "sscrp/rppub/components/image";
 import linkVoucherApi from '../../../../public/components/linkvoucher/linkvoucher'
 import linkBudgetApi from '../../../../public/components/linkbudget/linkbudget'
 import {updataFormData, updatacardTableData} from 'src/erm/sscrppublic/common/utils/changePageData';
 import {removeDisplayScale}  from "src/erm/sscrppublic/common/utils/dataFilter";
 const pageButton = window.presetVar.pageButton;
 const statusVar = window.presetVar.status;
 const head1 = window.presetVar.head.head1;
 const body1 = window.presetVar.body.body1;
 const pageId = window.presetVar.pageId;
 const { NCMessage } = base;
 
 let billtype = '2621';
 window.ntbCheck = 'false';
 function pageButtonClick() {
     return {
         // 暂存
         ['save_temp']: async () => {
            let props = this.props;
             props.cardTable.closeModel(body1);
             let allData = props.createMasterChildData(pageId, head1, body1);
             let filterEmptyData = filterEmptyRows(allData);
             //清除复制行主键，暂时先这样处理,目前平台api没有支持
             for (var i = 0; i < allData.body.accrued_detail.rows.length; i++) {
                 if (allData.body.accrued_detail.rows[i] && allData.body.accrued_detail.rows[i].status == 2) {
                     allData.body.accrued_detail.rows[i].values.pk_accrued_detail = {};
                 }
             }
             const rowData = props.cardTable.getVisibleRows(body1);
             const headAmount = props.form.getFormItemsValue('head', 'amount').value
             rowData.forEach((item)=>{
                let amountVal = _.get(item, `values.amount.value`, '')
                amountVal = amountVal ? amountVal : headAmount
                item.values.amount.value = amountVal
             })
             filterEmptyData.body[body1].rows = rowData
             //修改暂存的状态问题
             filterEmptyData.head.head.rows[0].status = window.presetVar.pageStatus[props.getUrlParam('status')]
            let billdataForFormula = props.createMasterChildData(window.presetVar.pageCode, head1, body1);
            let multiLang = props.MutiInit.getIntl(2011); //this.moduleId
            props.validateToSave(billdataForFormula, () =>{
                requestApi.saveTemp({
                    status: props.getUrlParam('status'),
                    accessorybillid: this.accessorybillid,
                    data: filterEmptyData,
                    success : (data) => {
                        props.form.setFormStatus(head1, statusVar.browse);
                        props.cardTable.setStatus(body1, statusVar.browse);
                        // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                        // props.form.setAllFormValue({ [head1]: data.data.head[head1] })
                        // // 设置表体数据
                        // data.data.body && props.cardTable.setTableData(body1, data.data.body[body1]);
                        // 设置表头数据
                        updataFormData(props, head1, data.data.head[head1]);
                        // 设置表体数据
                        data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                        // BTM 性能优化，变更页面数据更新方法
                        pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'),djzt:0, status: statusVar.browse, id: props.form.getFormItemsValue(head1, 'pk_accrued_bill').value });
                        routeChange.call(this, this.props,0)
                        props.button.setButtonsVisible({
                            // [pageButton.pageSave]: false,
                            [pageButton.pageEdit]: true,
                            [pageButton.billSubmit]: false
                        }); 
                    }
                })
            },body1 , null )
                
         },
         // 保存
         [pageButton.pageSave]: async () => {
             let props = this.props;
             window.presetVar.fromBtn = 'pageSave'
             props.cardTable.closeModel(body1);
             let checkResult = removeDisplayScale(props.form.isCheckNow('head') && props.cardTable.checkTableRequired());
             if (checkResult) {
                //校验附件是否必须上传
                const is_uploaded = await isUploadedAttachments.call(this, props)
                if(!is_uploaded) return

                let allData = props.createMasterChildData(pageId, head1, body1);
                let filterEmptyData = filterEmptyRows(allData);
                 //清除复制行主键，暂时先这样处理,目前平台api没有支持
                 for (var i = 0; i < allData.body.accrued_detail.rows.length; i++) {
                     if (allData.body.accrued_detail.rows[i] && allData.body.accrued_detail.rows[i].status == 2) {
                         allData.body.accrued_detail.rows[i].values.pk_accrued_detail = {};
                     }
                 }
                 filterEmptyData.body[body1].rows = props.cardTable.getVisibleRows(body1);
                 for (var i = 0; i < allData.body.accrued_detail.rows.length; i++) {
                      if (allData.body.accrued_detail.rows[i] && allData.body.accrued_detail.rows[i].status == 0) {
                       allData.body.accrued_detail.rows[i].values.pk_accrued_detail = {};
                   }
                }
                 let billdataForFormula = props.createMasterChildData(window.presetVar.pageCode, head1, body1);
                 let multiLang = props.MutiInit.getIntl(2011); //this.moduleId
                 props.validateToSave(billdataForFormula, () => {
                 
                     let vat_amount = props.form.getFormItemsValue(head1,"org_amount").value;
                     if(vat_amount==undefined||vat_amount==null||vat_amount==0||vat_amount=='0.00000000'){
                         toast({content:multiLang && multiLang.get('201102FYYT-0019')/*"金额不能为空!"*/,color:'warning'});
                         return;
                     }
                     requestApi.save({
                         status: props.getUrlParam('status'),
                         accessorybillid: this.accessorybillid,
                         data: filterEmptyData,
                         success: (data) => {
                             if (data.data.userjson && JSON.parse(data.data.userjson) && JSON.parse(data.data.userjson).bugetAlarm && JSON.parse(data.data.userjson).bugetAlarm.length>0) {
                                 promptBox({
                                     color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                     title: multiLang && multiLang.get('201102JCLF_C-0002'),//"提示信息"
                                     content: (multiLang && multiLang.get('201102JCLF_C-0003')) + JSON.parse(data.data.userjson).bugetAlarm + (multiLang && multiLang.get('201102JCLF_C-0004')),
                                     noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                     noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                     beSureBtnName: multiLang && multiLang.get('2011-0003'),
                                     cancelBtnName: multiLang && multiLang.get('2011-0002'),
                                     beSureBtnClick: () => {
                                         window.ntbCheck = 'true';
                                         pageButtonClick.call(this)[pageButton.pageSave]();
                                     }
                                     //cancelBtnClick: functionCancel  // 取消按钮点击调用函数,非必输
                                 })
                             }else{
                                 console.log('保存成功', data);
                                 this.auditSidebar.refreshSidebar()
                                 props.form.setFormStatus(head1, statusVar.browse);
                                 props.cardTable.setStatus(body1, statusVar.browse);
                                 // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                                 // props.form.setAllFormValue({ [head1]: data.data.head[head1] })
                                 // // 设置表体数据
                                 // data.data.body && props.cardTable.setTableData(body1, data.data.body[body1]);
                                 // 设置表头数据
                                 updataFormData(props, head1, data.data.head[head1]);
                                 // 设置表体数据
                                 data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                                 // BTM 性能优化，变更页面数据更新方法
                                 pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'), status: statusVar.browse, id: props.form.getFormItemsValue(head1, 'pk_accrued_bill').value });
                                 routeChange.call(this, this.props)
                                 /* props.button.setButtonsVisible({
                                     [pageButton.pageSave]: false,
                                     [pageButton.pageEdit]: true
                                 }); */
                             }
                         }
                     });
                 }, body1, null)
             }
         },
         // 修改
         [pageButton.pageEdit]: () => {
             let props = this.props;
 
             let scene = props.getUrlParam('scene');
             //获取单据编号
             let djbh = props.form.getFormItemsValue("head",['billno'])[0].value;
             let multiLang = props.MutiInit.getIntl(2011); //this.moduleId
             let canEdit = true;
             let isMaker = true;
             //来源于审批中心
             if(scene == 'approve' || scene == 'approvesce'){
                 isMaker = false;
                 //判断单据是否是当前用户待审批
                 ajax({
                     url: '/nccloud/riart/message/list.do',
                     async: false,
                     data: {
                         billno: djbh,
                         isread:'N'
                     },
                     success: result => {
                         if(result.data) {
                             if(result.data.total < 1){
                                 toast({content:multiLang&&multiLang.get('201102FYYT-0011')/**"当前单据已审批，不可进行修改操作!"**/,color:'warning'});
                                 canEdit =false;
                             }
                         }
                     }
                 });
             }
             //来源于我的作业
             if(scene == 'zycl'){
                 isMaker = false;
                 //判断单据是否是当前用户待处理
                 ajax({
                     url: '/nccloud/ssctp/sscbd/SSCTaskHandlePendingNumAction.do',
                     async: false,
                     data: {
                         billno: djbh
                     },
                     success: result => {
                         if(result.data) {
                             if(result.data.total < 1){
                                 toast({content:multiLang&&multiLang.get('201102FYYT-0012')/**"当前单据已处理，不可进行修改操作!"**/,color:'warning'});
                                 canEdit =false;
                             }
                         }
                     }
                 });
             }

            //特殊数据权限校验
            ajax({
                url: '/nccloud/erm/pub/ErmBillEditAction.do',
                async: false,
                data: {
                    'pk_org': props.form.getFormItemsValue("head",['pk_org'])[0].value,
                    'billid': props.form.getFormItemsValue("head",['pk_accrued_bill'])[0].value,
                    'billType':props.form.getFormItemsValue("head",['pk_tradetype'])[0].value
                },
                success: result => {
                    
                },
                error: (data) => {
                    canEdit = false;
                    toast({ content: data.message, color: 'danger' });
                }
            });

             if(!canEdit){
                 return;
             }
 
             if(isMaker){
                 //驳回不重走流程单据，设置不可编辑字段
                 requestApi.getUnEditAttributes({
                     data: {
                         'pk_org': props.form.getFormItemsValue("head",['pk_org'])[0].value,
                         'billid': props.form.getFormItemsValue("head",['pk_accrued_bill'])[0].value,
                         'billType':props.form.getFormItemsValue("head",['pk_tradetype'])[0].value
                     },
                     success: (data) => {
                         if(!(data==undefined || data.length == 0)){
                             let formobj = {};
                             let accrued_detailobj = [];
                             let accrued_verifyobj = [];
 
                             data.forEach((item) => {
                                 if(item.indexOf('accrued_detail.')>-1){
                                     accrued_detailobj.push(item.split('.')[1]);
                                 }else if(item.indexOf('accrued_verify.')>-1){
                                     accrued_verifyobj.push(item.split('.')[1]);
                                 }else{
                                     formobj[item] = true;
                                 }
                             })
                             props.form.setFormItemsDisabled('head',formobj)
                             props.cardTable.setColEditableByKey('accrued_detail',accrued_detailobj)
                             props.cardTable.setColEditableByKey('accrued_verify',accrued_verifyobj)
                         }
                     }
                 })
             } else {
                 //除制单人环节外的可编辑属性
                 requestApi.getUnEditAttributes({
                    data: {
                        'pk_org': props.form.getFormItemsValue("head",['pk_org'])[0].value,
                        'billid': props.form.getFormItemsValue("head",['pk_accrued_bill'])[0].value,
                        'billType':props.form.getFormItemsValue("head",['pk_tradetype'])[0].value
                    },
                    success: (data) => {
                        if(!(data==undefined || data.length == 0)){
                            let formobj = {};
                            let accrued_detailobj = [];
                            let accrued_verifyobj = [];

                            data.forEach((item) => {
                                if(item.indexOf('accrued_detail.')>-1){
                                    accrued_detailobj.push(item.split('.')[1]);
                                }else if(item.indexOf('accrued_verify.')>-1){
                                    accrued_verifyobj.push(item.split('.')[1]);
                                }else{
                                    formobj[item] = false;
                                }
                            })
                            props.form.setFormItemsDisabled('head',formobj)
                            props.cardTable.setColEditableByKey('accrued_detail',accrued_detailobj,false)
                            props.cardTable.setColEditableByKey('accrued_verify',accrued_verifyobj,false)
                        }
                    }
                })
             }
 
            pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { djzt:0,scene: props.getUrlParam('scene'), status: statusVar.edit, id: props.getUrlParam('id') });
            routeChange.call(this, this.props,0)
            let sceneout = this.props.getUrlParam('scene');
            if (sceneout == 'approve' || sceneout == 'approvesce' || sceneout == 'zycl') {
                props.button.setButtonsVisible({
                    [pageButton.pageSave]: true,
                    [pageButton.pageClose]: true,
                    [pageButton.billSaveSubmit]: false,
                    [pageButton.pageEdit]: false,
                    ['accrued_detail_Add']: true,
                    ['accrued_detail_Delete']: true,
                    ['accrued_detail_Copy']: true,
                    ['accrued_detail_Insert']: true

                });
            } else {
                props.button.setButtonsVisible({
                    [pageButton.pageSave]: true,
                    [pageButton.pageClose]: true,
                    [pageButton.pageEdit]: false,
                    ['accrued_detail_Add']: true,
                    ['accrued_detail_Delete']: true,
                    ['accrued_detail_Copy']: true,
                    ['accrued_detail_Insert']: true,
                });
            }
            if (window.djzt == '0') {
                props.button.setButtonsVisible({
                    ['save_temp']: true,
                });
            }
         },
         // 复制
         [pageButton.pageCopy]: () => {
             let props = this.props;
             pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'), status: statusVar.add, copyFromBillId: props.getUrlParam('id') });
             routeChange.call(this, this.props)
             window.assingUsers=[];
             //复制出来的单据要先清空附件产生的单据pk
             this.accessorybillid = '';
             this.setState({ billId: ''});
             let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
             this.props.button.setButtonTitle('fileManager', multiLang.get('201102FYYT-0014')/***'附件'**/ + ' ' + 0 + ' ');
         },
         // 删除
         [pageButton.pageDel]: () => {//删除单据
             let props = this.props;
             props.form.setFormStatus(head1, statusVar.browse);
             props.cardTable.setStatus(body1, statusVar.browse);
             let allData = props.createMasterChildData(pageId, head1, body1);
             requestApi.billRemove({
                 data: allData,
                 success: (data) => {
                     if (data.success) {
                         window.onbeforeunload=null;
                         window.top.close();
                     }
                 }
             });
         },
         [pageButton.billInvalid]: () => {//单据作废
             let props = this.props;
             window.presetVar.fromBtn = 'billInvalid'
             props.form.setFormStatus(head1, statusVar.browse);
             props.cardTable.setStatus(body1, statusVar.browse);
             let allData = props.createMasterChildData(pageId, head1, body1);
             requestApi.billInvalid({
                 data: allData,
                 success: (data) => {
                    this.auditSidebar.refreshSidebar()
                     updataFormData(props, head1, data.data.head[head1]);
                     data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                     pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'), status: statusVar.browse, id: props.getUrlParam('id') });
                     routeChange.call(this, this.props)
                 }
             });
         },
         [pageButton.pagePrint]: () => { //打印单据
             let vdata = {};
             vdata.billId = this.props.getUrlParam('id');
             vdata.billType = window.presetVar.billtype;
             ajax({
                 url: '/nccloud/erm/erbudgetmg/AccruedPrintValidaAction.do',
                 data: vdata,
                 success: (data) => {
                     if (!data.data.canPrint) {
                         NCMessage.create({ content: data.data.errMesg, color: 'error', position: 'bottom' });
                     } else {
                         print(
                             'pdf',  //支持两类: 'html'为模板打印, 'pdf'为pdf打印
                             '/nccloud/erm/pub/ErmPrintBillAction.do', //后台服务url
                             {
                                 billtype: billtype,  //单据类型
                                 funcode: (this.props.getUrlParam("appcode") == undefined || this.props.getUrlParam("appcode") == '') ? this.props.getSearchParam("c") : this.props.getUrlParam("appcode"),   //功能节点编码，即模板编码
                                 nodekey: '2621_IWEB',     //模板节点标识
                                 oids: [this.props.getUrlParam('id')]   // 功能节点的数据主键   oids含有多个元素(['1001A41000000000A9LR','1001A410000000009JDD'])时为批量打印,
                             }
                         )
                     }
                 }
             })
         }
         ,
         // 红冲
         [pageButton.billRedBack]: () => {//红冲
            let props = this.props;
            //先执行红冲前校验
            ajax({
                url: '/nccloud/erm/erbudgetmg/AccruedRedCheckAction.do',
                async: false,
                data: {
                    openbillid: props.getUrlParam('id')
                },
                success: () => {

                    props.specialOpenTo('../../../../erm/erbudgetmg/accrued/card/index.html', 
                    { scene: props.getUrlParam('scene'), status: statusVar.add, 
                    redBackFromBillId: props.getUrlParam('id'), pagecode: '201102FYYT_CARD' });

                }
            });
            
             
         }
         ,
         [pageButton.imageUpload]: () => {//影像扫描
             let props = this.props;
             let openbillid = props.getUrlParam('id');
             let billdata = props.createMasterChildData(pageId, head1, body1);
             var billInfoMap = {};
             //基础字段 单据pk,单据类型，交易类型，单据的组织
             billInfoMap.pk_billid = openbillid;
             billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
             billInfoMap.pk_tradetype = billdata.head.head.rows[0].values.pk_tradetype.value;
             billInfoMap.pk_org = billdata.head.head.rows[0].values.pk_org.value;
             //影像所需 FieldMap
             billInfoMap.BillType = billdata.head.head.rows[0].values.pk_tradetype.value;
             billInfoMap.BillDate = billdata.head.head.rows[0].values.creationtime.value;
             billInfoMap.Busi_Serial_No = billdata.head.head.rows[0].values.pk_accrued_bill.value;
             billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
             billInfoMap.OrgNo = billdata.head.head.rows[0].values.pk_org.value;
             billInfoMap.BillCode = billdata.head.head.rows[0].values.billno.value;
             billInfoMap.OrgName = billdata.head.head.rows[0].values.pk_org.display;
             billInfoMap.Cash = billdata.head.head.rows[0].values.amount.value;
             billInfoMap.userid = billdata.head.head.rows[0].values.creator.value;
             imageScan(billInfoMap, 'iweb');
         }
         ,
         [pageButton.imageShow]: () => {//影像查看
             let props = this.props;
             let openbillid = props.getUrlParam('id');
             let billdata = props.createMasterChildData(pageId, head1, body1);
             var billInfoMap = {};
             //基础字段 单据pk,单据类型，交易类型，单据的组织
             billInfoMap.pk_billid = openbillid;
             billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
             billInfoMap.pk_tradetype = billdata.head.head.rows[0].values.pk_tradetype.value;
             billInfoMap.pk_org = billdata.head.head.rows[0].values.pk_org.value;
             imageView(billInfoMap, 'iweb');
         }
         ,
         [pageButton.billSubmit]: async() => {//提交
            window.presetVar.fromBtn = 'saveSubmit'
             let props = this.props;
             let allData = props.createMasterChildData(pageId, head1, body1);
            //提交校验附件是否必须上传
            const is_uploaded = await isUploadedAttachments.call(this, props)
            if(!is_uploaded) return

             allData.uistate = props.getUrlParam('status');
             //清除复制行主键，暂时先这样处理,目前平台api没有支持
             for (var i = 0; i < allData.body.accrued_detail.rows.length; i++) {
                 if (allData.body.accrued_detail.rows[i] && allData.body.accrued_detail.rows[i].status == 2) {
                     allData.body.accrued_detail.rows[i].values.pk_accrued_detail = {};
                 }
             }
             requestApi.billSubmit({
                 data: allData,
                 success: (data) => {
                     //设置了指派
                     let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                     if (data.data.workflow && (data.data.workflow == 'approveflow' || data.data.workflow == 'workflow')) {
                         this.setState({
                             compositedata: data.data,
                             compositedisplay: true
                         });
                         
                         
                     } else {
                         this.setState({
                             compositedisplay: false
                         });
                         if (data.data.userjson && JSON.parse(data.data.userjson) && JSON.parse(data.data.userjson).bugetAlarm && JSON.parse(data.data.userjson).bugetAlarm.length>0) {
                             promptBox({
                                 color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                 title: multiLang && multiLang.get('201102JCLF_C-0002'),//"提示信息"
                                 content: (multiLang && multiLang.get('201102JCLF_C-0003')) + JSON.parse(data.data.userjson).bugetAlarm + (multiLang && multiLang.get('201102JCLF_C-0004')),
                                 noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                 noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                 beSureBtnName: multiLang && multiLang.get('2011-0003'),
                                 cancelBtnName: multiLang && multiLang.get('2011-0002'),
                                 beSureBtnClick: () => {
                                     window.ntbCheck = 'true';
                                     pageButtonClick.call(this)[pageButton.billSubmit]();
                                 },
                                 cancelBtnClick: () => {
                                    this.auditSidebar.refreshSidebar()
                                     pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'), status: statusVar.browse, id: props.form.getFormItemsValue(head1, 'pk_accrued_bill').value });
                                     routeChange.call(this, this.props)
                                     window.assingUsers = [];    //清空指派人信息
                                 }
                                 //cancelBtnClick: functionCancel  // 取消按钮点击调用函数,非必输
                             })
                         } else {
                           
                             //处理按钮状态
                             dataHandle.call(this,data.data.head[head1], props);
                             // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                             // //设置表头数据
                             // props.form.setAllFormValue({ [head1]: data.data.head[head1] })
                             // //设置表体数据
                             // data.data.body && this.props.cardTable.setTableData(body1, data.data.body[body1]);
                             // 设置表头数据
                             updataFormData(props, head1, data.data.head[head1]);
                             // 设置表体数据
                             data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                             // BTM 性能优化，变更页面数据更新方法
                             pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'), status: statusVar.browse, id: data.data.head[head1].rows[0].values.pk_accrued_bill.value });
                             routeChange.call(this, this.props)
                             window.assingUsers = [];    //清空指派人信息
                         }
                     }
                 }, error() {
                     props.button.setButtonsVisible({
                         [pageButton.billSubmit]: true,
                         [pageButton.pageSave]: true
                     });
                 }
             });
         }
         ,
         [pageButton.billSaveSubmit]: async() => {//保存提交
             let props = this.props;
             window.presetVar.fromBtn = 'saveSubmit'
            //提交校验附件是否必须上传
            const is_uploaded = await isUploadedAttachments.call(this, props)
            if(!is_uploaded) return
             let checkResult = props.form.isCheckNow('head') && props.cardTable.checkTableRequired();
             if(checkResult){
                 let allData = props.createMasterChildData(pageId, head1, body1);
                 let filterEmptyData = filterEmptyRows(allData);
                 allData = filterEmptyData;
                 let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                 allData.uistate = props.getUrlParam('status');
                 allData.body[body1].rows = props.cardTable.getVisibleRows(body1);
                 for (var i = 0; i < allData.body.accrued_detail.rows.length; i++) {
                    if (allData.body.accrued_detail.rows[i] && allData.body.accrued_detail.rows[i].status == 0) {
                     allData.body.accrued_detail.rows[i].values.pk_accrued_detail = {};
                 }
              }
                 let billdataForFormula = props.createMasterChildData(window.presetVar.pageCode, head1, body1);
                 if (this.accessorybillid == undefined || this.accessorybillid == 'undefined') {
                     this.accessorybillid = '';
                 }
                 props.validateToSave(billdataForFormula, () => {
                    let vat_amount = props.form.getFormItemsValue(head1,"org_amount").value;
                    if(vat_amount==undefined||vat_amount==null||vat_amount==0||vat_amount=='0.00000000'){
                        toast({content:multiLang && multiLang.get('201102FYYT-0019')/*"金额不能为空!"*/,color:'warning'});
                        return;
                    }
                     requestApi.billSubmit({
                         data: allData,
                         assignBillId : window.assignBillId,
                         accessorybillid : this.accessorybillid,
                         success: (data) => {
                             //设置了指派
                             if (data.data.workflow && data.data.billid && data.data.bill && (data.data.workflow == 'approveflow' || data.data.workflow == 'workflow')) {
                                 this.setState({
                                     compositedata: data.data,
                                     compositedisplay: true
                                 });
                                 window.assignBillId = data.data.billid;
                                 // 设置表头数据
                                 updataFormData(props, head1, data.data.bill.head[head1]);
                                 // 设置表体数据
                                 data.data.bill.body && updatacardTableData(props, body1, data.data.bill.body[body1]);
                                
                                
                            } else {
                                 this.setState({
                                     compositedisplay: false
                                 });
                                 if (data.data.userjson && JSON.parse(data.data.userjson) && JSON.parse(data.data.userjson).bugetAlarm && JSON.parse(data.data.userjson).bugetAlarm.length>0) {
                                     promptBox({
                                         color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                         title: multiLang && multiLang.get('201102JCLF_C-0002'),//"提示信息"
                                         content: (multiLang && multiLang.get('201102JCLF_C-0003')) + JSON.parse(data.data.userjson).bugetAlarm + (multiLang && multiLang.get('201102JCLF_C-0004')),
                                         noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                         noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                         beSureBtnName: multiLang && multiLang.get('2011-0003'),
                                         cancelBtnName: multiLang && multiLang.get('2011-0002'),
                                         beSureBtnClick: () => {
                                             window.ntbCheck = 'true';
                                             pageButtonClick.call(this)[pageButton.billSaveSubmit]();
                                         },
                                         cancelBtnClick: () => {
                                             if(props.form.getFormItemsValue(head1, 'pk_accrued_bill').value){
                                                 pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'), status: statusVar.edit, id: props.form.getFormItemsValue(head1, 'pk_accrued_bill').value });
                                             }else{
                                                 pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'), status: statusVar.add });
                                             }
                                             routeChange.call(this, this.props)
                                             this.auditSidebar.refreshSidebar()
                                             window.assingUsers = [];    //清空指派人信息
                                             window.sureAssign = false;
                                         } 
                                         //cancelBtnClick: functionCancel  // 取消按钮点击调用函数,非必输
                                     })
                                 } else {
                                    this.auditSidebar.refreshSidebar()
                                     //处理按钮状态
                                     dataHandle.call(this,data.data.head[head1], props);
                                     // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                                     // //设置表头数据
                                     // props.form.setAllFormValue({ [head1]: data.data.head[head1] })
                                     // //设置表体数据
                                     // data.data.body && this.props.cardTable.setTableData(body1, data.data.body[body1]);
                                     // 设置表头数据
                                     updataFormData(props, head1, data.data.head[head1]);
                                     // 设置表体数据
                                     data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                                     // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                                     pageTo.specialLinkTo('/erm/erbudgetmg/accrued/card/index.html', { scene: props.getUrlParam('scene'), status: statusVar.browse, id: data.data.head[head1].rows[0].values.pk_accrued_bill.value });
                                     routeChange.call(this, this.props)
                                     window.assingUsers = [];    //清空指派人信息
                                     window.sureAssign = false;
                                 }
                             }
                         }, error(data) {
                             props.button.setButtonsVisible({
                                 [pageButton.billSaveSubmit]: true,
                                 [pageButton.pageSave]: true
                             });
                         }
                     });
                 }, body1, null)
 
             }
         }
         ,
         [pageButton.billRecall]: () => {//收回
             let props = this.props;
             props.form.setFormStatus(head1, statusVar.browse);
             props.cardTable.setStatus(body1, statusVar.browse);
             let allData = props.createMasterChildData(pageId, head1, body1);
             requestApi.billRecall({
                 data: allData,
                 success: (data) => {
                    this.auditSidebar.refreshSidebar()
                     // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                     // //设置表头数据
                     // props.form.setAllFormValue({ [head1]: data.data.head[head1] })
                     // //设置表体数据
                     // data.data.body && this.props.cardTable.setTableData(body1, data.data.body[body1]);
                     // 设置表头数据
                     updataFormData(props, head1, data.data.head[head1]);
                     // 设置表体数据
                     data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                     // BTM 性能优化，变更页面数据更新方法
                     //处理按钮状态
                     dataHandle.call(this,data.data.head[head1], props);
                 }
             });
         }, [pageButton.fileManager]: () => {//附件管理
             let props = this.props;
             let billdata = props.createMasterChildData(pageId, head1, body1);
             let pk_billtype = billdata.head.head.rows[0].values.pk_tradetype.value;
             let billId = props.getUrlParam('id') || this.state.billId || "";
             // let billtype = props.getUrlParam('tradetype') || "";
             if (billId == "" && !this.state.showUploader) {
                 //去后台生成单据主键
                 requestApi.generatBillId({
                     data: { billtype: pk_billtype },
                     success: (data) => {
                         console.log(data);
                         let accessorypkfildname = data["pkfieldName"];
                         billId = data[accessorypkfildname];
                         this.accessorybillid = billId;
                         this.setState({
                             billId: billId,
                             showUploader: !this.state.showUploader
                         });
                     },
                     error: (data) => {
                         toast({content:data.message,color:'danger'});
                     }
                 });
             } else {
                 this.setState({
                     billId: billId,
                     showUploader: !this.state.showUploader
                 });
             }
         }, [pageButton.billView]: () => {//联查单据
             let props = this.props;
             props.form.setFormStatus(head1, statusVar.browse);
             props.cardTable.setStatus(body1, statusVar.browse);
             let allData = props.createMasterChildData(pageId, head1, body1);
             requestApi.billView({
                 data: allData,
                 success: (data) => {
                     if (data && data.data && data.data.jkdBillModel && data.data.jkdBillModel.rows) {
                         this.setState({ showModal: true });
                         let rowsdata = data.data.jkdBillModel.rows;
                         rowsdata && props.table.setAllTableData('billmodel', data.data.jkdBillModel);
                     }
 
                 }
             })
         }, [pageButton.pageClose]: () => {//取消
             let props = this.props;
             let billdata = props.createMasterChildData(pageId, head1, body1);
             let status =  props.getUrlParam('status');
             let billId = props.getUrlParam('id') || props.getUrlParam('copyFromBillId');
             if(status ==  statusVar.edit || status ==  statusVar.add){ //从拷贝单据回退时是add状态
                 requestApi.query({
                     data: {
                         "openbillid": billId,
                         "pagecode": window.presetVar.pageCode
                     },
                     success: (data) => {
                         if(data.data){
                             if (data.data.head[head1].rows[0].values.effectstatus.value == 1) {//已生效才显示核销预提页签
                                 this.setState({ isEffect: true });
                             } else {
                                 this.setState({ isEffect: false });
                             }
                             props.form.setAllFormValue({ [head1]: data.data.head[head1] });
                             //设置表体数据
                             props.cardTable.setTableData(body1, data.data.bodys[body1]);
                             //重新处理按钮
                             pageTo.specialLinkTo(location.pathname, {
                                 scene: props.getUrlParam('scene'),
                                 status: statusVar.browse,
                                 id: billId
                             });
                             routeChange.call(this, this.props)
                         }else{
                             window.onbeforeunload=null;
                             window.top.close();
                         }
                         this.auditSidebar.refreshSidebar()
                     
                     }
                 })
 
        }else{
         window.onbeforeunload=null;
             window.top.close();
        }
         },
         [pageButton.linkVoucher]: () => {
             let props = this.props;
             let paramurl = getRequest1(parent.window.location.hash);
             //如果没取到应用主键再取一下外层,主要适配作业任务打开单据时联查凭证
             if (!paramurl.ar) {
                 paramurl = getRequest1(parent.parent.window.location.hash);
             }
             let multiLang = props.MutiInit.getIntl(2011); //this.moduleId
             if (paramurl.ar) {
                 let billdata = props.createMasterChildData(pageId, head1, body1);
                 if (billdata.head.head.rows.length) {
                     linkVoucherApi.link({
                         data: {
                             props: props,
                             record: {
                                 pk_billtype: billdata.head.head.rows[0].values.pk_tradetype.value,
                                 pk_group: billdata.head.head.rows[0].values.pk_group.value,
                                 pk_org: billdata.head.head.rows[0].values.pk_org.value,
                                 relationID: billdata.head.head.rows[0].values.pk_accrued_bill.value
                             },
                             appid: paramurl.ar
                         }
                     })
                 }
             } else {
                 toast({ content: multiLang&&multiLang.get('201102FYYT-0013')/**'联查凭证失败，缺少应用主键'**/, color: 'danger' });
             }
         },
         [pageButton.linkBudget]: () => {
             let props = this.props;
             let billdata = props.createMasterChildData(pageId, head1, body1);
             linkBudgetApi.link({
                 data: {
                     "tradetype": billdata.head.head.rows[0].values.pk_tradetype.value,
                     "openbillid": billdata.head.head.rows[0].values.pk_accrued_bill.value
                 },
                 success: (data) => {
                     this.setState({
                         sourceData: data,
                         showLinkBudget: true
                     })
                 }
             })
         },
         [pageButton.billApprove]: () => {
             let props = this.props;
             let billdata = props.createMasterChildData(pageId, head1, body1);
             let pk_billtype = billdata.head.head.rows[0].values.pk_tradetype.value;
             let billId = billdata.head.head.rows[0].values.pk_accrued_bill.value || props.getUrlParam('id') || this.state.billId || "";
             this.setState({
                 ShowApproveDetail: true,
                 billId: billId,
                 billtype: pk_billtype
             });
         },
         //制单按钮逻辑
         [pageButton.pageMakebill]: () => {
             let props = this.props;
             let pk_accrued_bill=props.form.getFormItemsValue("head","pk_accrued_bill").value;//表头的单据主键
             let pk_tradetype=props.form.getFormItemsValue("head","pk_tradetype").value;//单据类型编码
             //后台接口业务参数
             let makebillArr = {
                 "pk_accrued_bill":pk_accrued_bill,
                 "pk_tradetype":pk_tradetype
             };
             console.log("制单按钮参数："+makebillArr);
             requestApi.makebill({
                 data:makebillArr,
                 success:(data)=>{
                 console.log("后台制单逻辑响应参数"+data);
                 let srccode = "erm" + data.cachekey;
                 cacheTools.set("erm" + data.cachekey, data.pklist);
                 //跳转
                 props.openTo(data.url, {
                     status: 'edit',
                     appcode: data.appcode,
                     pagecode: data.pagecode,
                     pagekey:'',
                     ifshowQuery:true,
                     n: '凭证生成',//'凭证生成'
                     scene: srccode
                 });
                 
                 },
                 error:(data)=>{
                     toast({ content: data.message, color: 'danger' });
                 }
             });
 
         }
     }
 }
 
 /*
  * @method   if条件下为false   除去NaN、0、-0、false   剩余undefined、null、""
  * @author   add by yangguoqiang @18/03/19
  * @params
  *     condition     {any}
  * @return   {boolean}       返回ture/false
  * @demo     isWrong('')    因为后台返回数据不规范
  */
 function isWrongFalse(param) {
     return typeof param === 'undefined' || param === null || param === '' || param === false;
 }
 
 
 /**
  * modify by qiufh@yonyou.com from the platform source
  * 32、移除没有输入内容，所有的空行
  * @param  tableId   meta的id号
  * @param  key       data的键值
  */
 function filterEmptyRows(allData, keys) {
     let filterData;
     if (allData.body.accrued_detail.rows && allData.body.accrued_detail.rows.length > 0) {
         allData.body.accrued_detail.rows.forEach((item, index) => {
             let values = item.values;
             let tempArr = Object.keys(values).filter(item => item != 'numberindex');
             if (Array.isArray(keys)) {
                 tempArr = tempArr.filter(function (val) {
                     return keys.every(function (key) {
                         return val !== key
                     })
                 })
             }
             // flag 为true 说明每个字段  （要不然不是对象  TODO ? 应该不需要判断 略）   或者 没值
             let flag = tempArr.every(one => (isWrongFalse(values[one].value)))
             flag && (delete allData.body.accrued_detail.rows[index])
         })
         allData.body.accrued_detail.rows = allData.body.accrued_detail.rows.filter(item => !!item)
         filterData = allData;
         return filterData;
     }
     return allData;
 }
 
 export default pageButtonClick;
 
 // 1903方式，参数列表在url中，改为根据url的page属性从session中获取
 // function getRequest1(url) {
 //     if (!url)
 //         url = document.location.search;
 //     var theRequest = new Object();
 //     if (url.indexOf("?") != -1) {
 //         var str = url.substring(url.indexOf("?") + 1);
 //         var strs = str.split("&");
 //         for (var i = 0; i < strs.length; i++) {
 //             theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
 //         }
 //     }
 //     return theRequest;
 // }
 function getRequest1(url) {
     if (!url)
         url = document.location.search;
     let sessionInfo = ""
     if (url.indexOf("page=") != -1) {
         //获取url中页面page参数 1909url中参数仅有page
         var page;
         if (url.indexOf("?") != -1) {
             var str = url.substring(url.indexOf("?") + 1);
             var strs = str.split("&");
             page = strs[0].split("=")[1];
         }
 
         //根据page获取session storage中原来1903url中的参数
         var msg = getGlobalStorage('sessionStorage', 'NCCAPPURL');
         msg = JSON.parse(msg);
         sessionInfo = msg[page];
     } else if (url.indexOf("?") != -1) {
         sessionInfo = url.substring(url.indexOf("?") + 1);        
     } else {
         sessionInfo = url;
     }
     
 
     //解析参数
     var theRequest = new Object();
     var strs = sessionInfo.split("&");
     for (var i = 0; i < strs.length; i++) {
         theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
     }
     return theRequest;
 }